package com.hp.ecs.xqa.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {

	/** yyyyMMdd */
	public static final String COMPACT_DATE_PATTERN = "yyyyMMdd";

	/** yyyy-MM-dd */
	public static final String DATE_PATTERN = "yyyy-MM-dd";

	/** yyyy-MM-dd HH:mm:ss */
	public static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

	/** yyyy-MM-dd HH:mm */
	public static final String TRIM_SECOND_PATTERN = "yyyy-MM-dd HH:mm";

	/** yyyyMMdd HH:mm */
	public static final String COMPACT_TRIM_SECOND_PATTERN = "yyyyMMdd HH:mm";

	/** pattern: yyyy-MM-dd */
	public static Date parse(String str) {
		return parse(str, DATE_PATTERN);
	}

	private static final ThreadLocal<Date> DATE_TL = new ThreadLocal();

	public static Date current() {
		Date date = DATE_TL.get();
		if (date == null || System.currentTimeMillis() - date.getTime() > 1000) {
			date = new Date();
			DATE_TL.set(date);
		}
		return date;
	}

	public static Date parse(String str, String pattern) {
		DateFormat parser = new SimpleDateFormat(pattern);
		try {
			return parser.parse(str);
		} catch (ParseException e) {
			throw new IllegalArgumentException("Can't parse " + str + " using " + pattern, e);
		}
	}

	/**
	 * 根据时间返回字符串:yyyy-MM-dd
	 */
	public static String format(Date date) {
		return format(date, DATE_PATTERN);
	}

	public static String format(Date date, String pattern) {
		if (date == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(pattern);
		return formatter.format(date);
	}
}
